package org.ioflow.utils
{
	import flash.utils.Dictionary;

	public final class UrlHelper
	{	
		private var m_url:String;
		
		private var m_host:String;
		private var m_port:String;
		private var m_protocol:String;
		private var m_path:String;
		private var m_paramsString:String;
		private var m_parameters:Object;   

		
		public function UrlHelper(Url:String, parseParams:Boolean = false)
		{
			super();
			m_url = Url;
			const reg:RegExp = /(?P<protocol>[a-zA-Z]+) : \/\/  (?P<host>[^:\/]*) (:(?P<port>\d+))?  ((?P<path>[^?]*))? ((?P<parameters>.*))? /x;
			const results:Array = reg.exec(Url);
			m_protocol = results.protocol
			m_host = results.host;
			m_port = results.port;
			if (m_port == "")
			{
				m_port = "80";
			}
			m_path = results.path;
			m_paramsString = results.parameters;
			if (parseParams)
			{
				m_parameters = new Object();
				const paramsStr:String = m_paramsString.charAt(0) == "?"?m_paramsString.substring(1):m_paramsString;
				const params:Array = paramsStr.split("&");
				for each(var paramStr:String in params)
				{
					const splitedParam:Array = paramStr.split("=");
					m_parameters[splitedParam[0]] = splitedParam[1];
				}
			}
			else
			{
				m_parameters = null;
			}
			
			
		}
		
		public function toUrlString():String
		{
			return m_protocol + '://' + m_host + (m_port == "80"?'':':' + m_port) + m_path + buildParams();
		}
		
		private function buildParams():String
		{
			if (m_parameters == null)
			{
				return m_paramsString;
			}
			else
			{
				const vec:Vector.<String> = new Vector.<String>();
				for(var key:String in m_parameters)
				{
					vec.push(key + '=' + m_parameters[key]);
				}
				return vec.length > 0?'?' + vec.join("&"):"";
			}
		}
		
		public function set host(value:String):void
		{
			m_host = value;
		}
		
		public function set port(value:String):void
		{
			m_port = value;
		}
		
		public function set protocol(value:String):void
		{
			m_protocol = value;
		}
		
		public function set path(value:String):void
		{
			m_path = value;
		}
		
		public function set parameters(value:Object):void
		{
			m_parameters = value;
		}
		
		
		
		
		public function get host():String
		{
			return m_host;
		}
		
		public function get port():String
		{
			return m_port;
		}
		
		public function get protocol():String
		{
			return m_protocol;
		}
		
		public function get path():String
		{
			return m_path;
		}
		
		public function get parameters():Object
		{
			return m_parameters;
		}
		
		public function get url():String
		{
			return m_url;
		}
		
		public function get parametersString():String
		{
			return m_paramsString;
		}
		
		public function toString():String
		{
			return JSON.stringify({protocol:m_protocol, host:m_host, port:m_port, path:m_path, params:m_parameters==null?m_paramsString:m_parameters});
		}
	}
}